import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactEcharts from 'echarts-for-react';
import { subscribeComp } from '@/services/bajaService';


class EchartsGauge extends Component {

  static defaultProps = {
    title: '',
    fontSize: '16px',
    min: 0,
    max: 100,
    unit: 'KWH'
  }

  constructor(props) {
    super(props);
    const {title, fontSize, min, max, unit} = this.props;
    this.option = this.buildOption(title, parseInt(fontSize), min, max, unit);
    this.sub = null;
  }

  buildOption = (title, fontSize, min, max, unit) => ({
    title: {
      text: title,
      left: 'center',
      textStyle: {
        color: 'white',
        fontSize
      }
    },
    toolbox: {
      show: false,
    },
    series: [{
      type: 'gauge',
      radius: '90%',
      center: ['50%', '60%'],
      min: min,
      max: max,
      pointer: {
        width: 3,//指针的宽度
        length: '90%', //指针长度，按照半圆半径的百分比
      },
      axisLine: {
        lineStyle: {
          width: 20
        }
      },
      axisLabel: {            // 坐标轴小标记
        textStyle: {       // 属性lineStyle控制线条样式
          color: 'white',
          fontSize: fontSize*0.8,
        },
      },
      detail: {
        formatter: '\n{value}\n' + unit,
        textStyle: {
          color: 'white',
          fontSize: fontSize*0.8,
        },
      },
      data: [{
        value: 50
      }],
    }]
  })

  updateChart = (value) => {
    this.option.series[0].data[0].value = value;
    if(this.echarts) {
      this.echarts.getEchartsInstance().setOption(this.option);
    }
  }

  subscribeChart = () => {
    subscribeComp(this.props.ord, (component)=>{
      const value = parseFloat(component.getOut().getValue().toFixed(2));
      this.updateChart(value);
    }).then((sub)=> {
      this.sub = sub;
    });
  }

  componentDidMount() {
    this.subscribeChart();
  }

  componentWillUnmount() {
    if(this.sub && this.sub.unsubscribeAll) {
      this.sub.unsubscribeAll();
      this.sub.detach();
    }
  }

  render() {
    return (
      <ReactEcharts
        ref={(e) => { this.echarts = e; }}
        notMerge={true}
        lazyUpdate={true}
        option={this.option}
        style={{width:'100%',height:'100%'}}
      />
    );
  }
}

EchartsGauge.propTypes = {
  ord: PropTypes.string.isRequired,
  title: PropTypes.string,
  fontSize: PropTypes.string,
  min: PropTypes.number,
  max: PropTypes.number,
  unit: PropTypes.string,
}

export default EchartsGauge;
